
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MPMediaPickerController.h>
#import "TCVideoRecordViewController.h"
#import "TXUGCRecord.h"
#import "TCVideoPublishController.h"
#import "TCVideoEditViewController.h"
#import "TCVideoRecordMusicView.h"
#import "TCVideoRecordProcessView.h"
#import "V8HorizontalPickerView.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "TCBGMListViewController.h"
#import "BeautySettingPanel.h"
#import "MBProgressHUD.h"
#import "UIAlertView+BlocksKit.h"
#import "TXVideoEditer.h"
#import "MHVideoEditViewModel.h"
#import "MHVideoRecordViewModel.h"
#import "QBImagePickerController.h"
#import "UIButton+ImageTitleSpacing.h"
#import "MHNavigationController.h"
#import "MHBGMListViewModel.h"
#define BUTTON_RECORD_SIZE          75
#define BUTTON_CONTROL_SIZE         40
#define MAX_RECORD_TIME             15
#define MIN_RECORD_TIME             2
#define BUTTON_PROGRESS_HEIGHT      4
#define BUTTON_MASK_HEIGHT          170
#define BUTTON_SPEED_HEIGHT         34
#define BUTTON_SPEED_INTERVAL       30
#define BUTTON_SPEED_COUNT          5
#define BUTTON_SPEED_CHANGE_WIDTH   50
#define BUTTON_SPEED_CHANGE_HEIGHT  34


typedef NS_ENUM(NSInteger,SpeedMode)
{
    SpeedMode_VerySlow,
    SpeedMode_Slow,
    SpeedMode_Standard,
    SpeedMode_Quick,
    SpeedMode_VeryQuick,
};

@implementation RecordMusicInfo
@end

#if POD_PITU
#import "MCCameraDynamicView.h"
#import "MaterialManager.h"
#import "MCTip.h"
@interface TCVideoRecordViewController () <MCCameraDynamicDelegate,VideoRecordMusicViewDelegate,BeautySettingPanelDelegate,BeautyLoadPituDelegate,QBImagePickerControllerDelegate>

@end
#endif

@interface TCVideoRecordViewController()<TXUGCRecordListener,V8HorizontalPickerViewDelegate,V8HorizontalPickerViewDataSource,MPMediaPickerControllerDelegate,TCBGMControllerListener,TXVideoJoinerListener,QBImagePickerControllerDelegate>
{
    BOOL                            _cameraFront;
    BOOL                            _lampOpened;
    BOOL                            _vBeautyShow;
    
    int                             _beautyDepth;
    int                             _whitenDepth;
    int                             _redDepth;
    BOOL                            _cameraPreviewing;
    BOOL                            _videoRecording;
    UIView *                        _videoRecordView;
    UIButton *                      _btnStartRecord;
    UIButton *                      _btnCamera;
    UIButton *                      _btnLamp;
    UIButton *                      _btnBeauty;
    UILabel *                       _recordTimeLabel;
    
    
    UIView *                        _beautyPage;
    UIView *                        _filterPage;
    UIView *                        _speedView;
    
    UIButton *                      _btnNext;
    UIButton *                      _btnRatio;
    UIButton *                      _btnRatio43;
    UIButton *                      _btnRatio11;
    UIButton *                      _btnRatio169;
    UILabel  *                      _labelRatio43;
    UILabel  *                      _labelRatio11;
    UILabel  *                      _labelRatio169;
    UIButton *                      _btnMusic;
    UIButton *                      _btnFlash;
    UIButton *                      _btnUploadLocal;
    UIButton *                      _btnDelete;
    UIButton *                      _beautyBtn;
    UIButton *                      _filterBtn;
    UIButton *                      _speedChangeBtn;
    
    UISlider*                       _sdBeauty;
    UISlider*                       _sdWhitening;
    V8HorizontalPickerView *        _filterPickerView;
    NSMutableArray *                _filterArray;
    int                             _filterIndex;
    
    BOOL                            _navigationBarHidden;
    BOOL                            _statusBarHidden;
    BOOL                            _appForeground;
    BOOL                            _isPaused;
    
    UIButton              *_motionBtn;
#if POD_PITU
    MCCameraDynamicView   *_tmplBar;
    NSString              *_materialID;
#else
    UIView                *_tmplBar;
#endif
    UIButton              *_greenBtn;
    V8HorizontalPickerView  *_greenPickerView;
    NSMutableArray *_greenArray;
    
    TCBGMListViewController*        _bgmListVC;
    
    UILabel               *_beautyLabel;
    UILabel               *_whiteLabel;
    UILabel               *_bigEyeLabel;
    UILabel               *_slimFaceLabel;
    
    UISlider              *_sdBigEye;
    UISlider              *_sdSlimFace;
    
    int    _filterType;
    int    _greenIndex;;
    
    float  _eye_level;
    float  _face_level;
    
    CGRect                    _btnRatioFrame;
    UIView *                  _mask_buttom;
    NSMutableArray *          _speedBtnList;
    NSInteger                 _speedBtnSelectTag;
    //    NSString*                 self.BGMPath;
    CGFloat                   _BGMDuration;
    
    int                       _deleteCount;
    float                     _zoom;
    BOOL                      _isBackDelete;
    BOOL                      _isFlash;
    
    TXVideoAspectRatio        _videoRatio;
    TCVideoRecordMusicView *  _musicView;
    TCVideoRecordProcessView* _progressView;
    TXVideoAspectRatio        _aspectRatio;
    SpeedMode                 _speedMode;
    
    BeautySettingPanel *      _vBeauty;
    MBProgressHUD*            _hub;
    CGFloat                   _bgmBeginTime;
    BOOL                      _bgmRecording;
    
    TXVideoJoiner *           _videoJoiner;
    NSString *                _videoOutputPath;
}
@property(nonatomic, strong) MHVideoRecordViewModel *viewModel;
@property(nonatomic, assign)  CGFloat                 currentRecordTime;
@end


@implementation TCVideoRecordViewController
@dynamic viewModel;

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        _cameraFront = YES;
        _lampOpened = NO;
        _vBeautyShow = NO;
        
        _beautyDepth = MHVideoRecordBeautyLevel;
        _whitenDepth = MHVideoRecordWhiteLevel;
        _redDepth = MHVideoRecordRedLevel;
        _cameraPreviewing = NO;
        _videoRecording = NO;
        
        _currentRecordTime = 0;
        _greenArray = [NSMutableArray new];
        [_greenArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"无";
            v.file = nil;
            v.face = [UIImage imageNamed:@"greens_no"];
            v;
        })];
        [_greenArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"卡通";
            v.file = [[NSBundle mainBundle] URLForResource:@"goodluck" withExtension:@"mp4"];;
            v.face = [UIImage imageNamed:@"greens_1"];
            v;
        })];
        [_greenArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"DJ";
            v.file = [[NSBundle mainBundle] URLForResource:@"2gei_5" withExtension:@"mp4"];
            v.face = [UIImage imageNamed:@"greens_2"];
            v;
        })];
        
        _filterIndex = 0;
        _filterArray = [NSMutableArray new];
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"原图";
            v.face = [UIImage imageNamed:@"orginal"];
            v;
        })];
        
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"美白";
            v.face = [UIImage imageNamed:@"fwhite"];
            v;
        })];
        
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"浪漫";
            v.face = [UIImage imageNamed:@"langman"];
            v;
        })];
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"清新";
            v.face = [UIImage imageNamed:@"qingxin"];
            v;
        })];
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"唯美";
            v.face = [UIImage imageNamed:@"weimei"];
            v;
        })];
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"粉嫩";
            v.face = [UIImage imageNamed:@"fennen"];
            v;
        })];
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"怀旧";
            v.face = [UIImage imageNamed:@"huaijiu"];
            v;
        })];
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"蓝调";
            v.face = [UIImage imageNamed:@"landiao"];
            v;
        })];
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"清凉";
            v.face = [UIImage imageNamed:@"qingliang"];
            v;
        })];
        [_filterArray addObject:({
            V8LabelNode *v = [V8LabelNode new];
            v.title = @"日系";
            v.face = [UIImage imageNamed:@"rixi"];
            v;
        })];
        
        _videoRatio = VIDEO_ASPECT_RATIO_9_16;
        [TXUGCRecord shareInstance].recordDelegate = self;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onAudioSessionEvent:)
                                                     name:AVAudioSessionInterruptionNotification
                                                   object:nil];
        
        _appForeground = YES;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)dealloc
{
    [[TXUGCRecord shareInstance].partsManager deleteAllParts];
     [[TXUGCRecord shareInstance] pauseAudioSession];
    [[TXUGCRecord shareInstance] stopRecord];
//    [[TXUGCRecord shareInstance] stopCameraPreview];
//
//
////    [self stopVideoRecord];
//    [[TXUGCRecord shareInstance] stopRecord];
//    [TXUGCRecord shareInstance].recordDelegate = nil;
    
//    [[TXUGCRecord shareInstance].partsManager deleteAllParts];
//    [self stopCameraPreview];
//    [[TXUGCRecord shareInstance] stopRecord];
//    [TXUGCRecord shareInstance].recordDelegate = nil;
    

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self initUI];
    [self initBeautyUI];
    
//    MHBGMListViewModel *listModel = [[MHBGMListViewModel alloc] initWithServices:self.viewModel.services params:nil];
//    _bgmListVC = [[TCBGMListViewController alloc] initWithViewModel:listModel];
//    [_bgmListVC setBGMControllerListener:self];
    _videoJoiner = [[TXVideoJoiner alloc] initWithPreview:nil];
    _videoJoiner.joinerDelegate = self;
    _videoOutputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"outputRecord.mp4"];
    //临时解决拍视频闪退的问题;
     [[TXUGCRecord shareInstance] stopCameraPreview];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _navigationBarHidden = self.navigationController.navigationBar.hidden;
    _statusBarHidden = [UIApplication sharedApplication].statusBarHidden;
    [self.navigationController setNavigationBarHidden:YES];
    [[UIApplication sharedApplication]setStatusBarHidden:YES];
    if (_cameraPreviewing == NO) {
        [self startCameraPreview];
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[TXUGCRecord shareInstance] resumeAudioSession];
        });
    }
   
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:_navigationBarHidden];
    [[UIApplication sharedApplication]setStatusBarHidden:_statusBarHidden];
    
    
    //    [self stopVideoRecord];
    //    [[TXUGCRecord shareInstance] resumeAudioSession];
}

-(void)onAudioSessionEvent:(NSNotification*)notification
{
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        // 在10.3及以上的系统上，分享跳其它app后再回来会收到AVAudioSessionInterruptionWasSuspendedKey的通知，不处理这个事件。
        if ([info objectForKey:@"AVAudioSessionInterruptionWasSuspendedKey"]) {
            return;
        }
        _appForeground = NO;
        if (!_isPaused && _videoRecording)
            [self onBtnRecordStartClicked];
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            _appForeground = YES;
        }
    }
}

- (void)onAppDidEnterBackGround:(UIApplication*)app
{
    _appForeground = NO;
    if (!_isPaused && _videoRecording)
        [self onBtnRecordStartClicked];
    
}

- (void)onAppWillEnterForeground:(UIApplication*)app
{
    _appForeground = YES;

}

-(void)onBtnPopClicked
{
    NSArray *videoPaths = [[TXUGCRecord shareInstance].partsManager getVideoPathList];
    if (videoPaths.count > 0) {
        UIAlertView *alert = [UIAlertView bk_showAlertViewWithTitle:@"您确定要退出当前录制 ? 退出录制后，当前录制的片段会被删除" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                
                
                [self stopCameraPreview];
                [[TXUGCRecord shareInstance] stopRecord];
                [TXUGCRecord shareInstance].recordDelegate = nil;
                [[TXUGCRecord shareInstance].partsManager deleteAllParts];
                [self.viewModel.services dismissViewModelAnimated:YES completion:nil];
            }
        }];
        [alert show];
    }else{
        
        [self stopCameraPreview];
        [[TXUGCRecord shareInstance] stopRecord];
        [TXUGCRecord shareInstance].recordDelegate = nil;
        [[TXUGCRecord shareInstance].partsManager deleteAllParts];
        [self.viewModel.services dismissViewModelAnimated:YES completion:nil];
        [AXAppDelegate sharedDelegate].currentSong = nil;
    }
}

- (void)handlePinch:(UIPinchGestureRecognizer*)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
        [[TXUGCRecord shareInstance] setZoom:MIN(MAX(1.0, _zoom * recognizer.scale),5.0)];
    }else if (recognizer.state == UIGestureRecognizerStateEnded){
        _zoom = MIN(MAX(1.0, _zoom * recognizer.scale),5.0);
        recognizer.scale = 1;
    }
}

#pragma mark ---- Common UI ----
-(void)initUI
{
    self.title = @"";
    self.view.backgroundColor = UIColor.blackColor;
    _videoRecordView = [[UIView alloc] initWithFrame:self.view.bounds];
    _videoRecordView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:_videoRecordView];
    UIPinchGestureRecognizer* pinchGensture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    [_videoRecordView addGestureRecognizer:pinchGensture];
    UIButton *btnPop = [UIButton buttonWithType:UIButtonTypeCustom];
    btnPop.bounds = CGRectMake(0, 0, BUTTON_CONTROL_SIZE, BUTTON_CONTROL_SIZE);
    btnPop.center = CGPointMake(7 + BUTTON_CONTROL_SIZE / 2, 20 + BUTTON_CONTROL_SIZE / 2 + zh_topSafeAreaHeight() );
    [btnPop setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [btnPop addTarget:self action:@selector(onBtnPopClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnPop];
    
    
    
    
    CGFloat btnMusicSize = 44;
    _btnMusic = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnMusic.bounds = CGRectMake(0, 0, btnMusicSize*2, btnMusicSize );
    [_btnMusic setTitle:@"选择音乐" forState:0];
    _btnMusic.imageView.contentMode = UIViewContentModeScaleAspectFill;
    _btnMusic.hidden = ![AXAppDelegate sharedDelegate].isAuthorizationExpired;
    _btnMusic.titleLabel.font = MHRegularFont_12;
    [_btnMusic addTarget:self action:@selector(onBtnMusicClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnMusic];
    [_btnMusic layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft
                               imageTitleSpace:5];
    _btnMusic.center = CGPointMake(self.view.centerX,  20 + BUTTON_CONTROL_SIZE / 2 + zh_topSafeAreaHeight());
    //     _btnMusic.centerY = btnPop.centerY;
    //    _musicView = [[TCVideoRecordMusicView alloc] initWithFrame:CGRectMake(0, self.view.bottom - 268 * kScaleY, self.view.width, 268 * kScaleY) needEffect:NO];
    //    _musicView.hidden = YES;
    
    
    @weakify(self);
    [RACObserve(self, BGMPath) subscribeNext:^(NSString   *path) {
        @strongify(self);
        if (path.length <= 0) {
            [self->_btnMusic setImage:[UIImage imageNamed:@"icon_video_choosemusic"] forState:0];
            [self->_btnMusic setTitle:@"选择音乐" forState:0];
            //            [self->_btnMusic sizeToFit];
            //            [self resumeBGM];
            //            [self onVoiceValueChange:1];
            self->_btnMusic.center = CGPointMake(self.view.centerX,  20 + BUTTON_CONTROL_SIZE / 2 + zh_topSafeAreaHeight());
        }else
        {
            [self->_btnMusic setImage:[UIImage imageNamed:@"icon_video_choosemusicsel"] forState:0];
            //            [self onVoiceValueChange:0];
//            self->_videoRecording = NO;
        }
    }];
    
    _musicView.delegate = self;
    _musicView.hidden = YES;
    [self.view addSubview:_musicView];
    
    _mask_buttom = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - BUTTON_MASK_HEIGHT, self.view.frame.size.width, BUTTON_MASK_HEIGHT)];
    [_mask_buttom setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_mask_buttom];
    
    CGFloat recordBtnSize = 82;
    _btnStartRecord = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, recordBtnSize, recordBtnSize)];
    _btnStartRecord.center = CGPointMake(self.view.frame.size.width / 2, self.view.height - recordBtnSize / 2 - 20);
    [_btnStartRecord setImage:[UIImage imageNamed:@"start_record"] forState:UIControlStateNormal];
    [_btnStartRecord setBackgroundImage:[UIImage imageNamed:@"start_record"] forState:UIControlStateNormal];
    [_btnStartRecord addTarget:self action:@selector(onBtnRecordStartClicked) forControlEvents:UIControlEventTouchDown];
    [_btnStartRecord addTarget:self action:@selector(onBtnRecordStartClicked) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
    [self.view addSubview:_btnStartRecord];
    
    _btnCamera = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnCamera.bounds = CGRectMake(0, 0, BUTTON_CONTROL_SIZE, BUTTON_CONTROL_SIZE + 22);
    _btnCamera.center = CGPointMake( self.view.right - 15 - BUTTON_CONTROL_SIZE / 2, zh_topSafeAreaHeight() + 80);
    [_btnCamera setImage:[UIImage imageNamed:@"camera_record"] forState:UIControlStateNormal];
    [_btnCamera setImage:[UIImage imageNamed:@"camera_record"] forState:UIControlStateHighlighted];
    [_btnCamera setTitle:@"转换" forState:0];
    _btnCamera.titleLabel.textColor = MHWhiteTextColor;
    _btnCamera.titleLabel.font = MHRegularFont_12;
    [_btnCamera addTarget:self action:@selector(onBtnCameraClicked) forControlEvents:UIControlEventTouchUpInside];
    [_btnCamera layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop
                                imageTitleSpace:5];
    [self.view addSubview:_btnCamera];
    
    _btnBeauty = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnBeauty.bounds = CGRectMake(0, 0, btnMusicSize, btnMusicSize + 22);
    [_btnBeauty setTitle:@"美颜" forState:0];
    _btnBeauty.titleLabel.textColor = MHWhiteTextColor;
    _btnBeauty.titleLabel.font = MHRegularFont_12;
    _btnBeauty.center = CGPointMake(self.view.right - 15 - BUTTON_CONTROL_SIZE / 2, _btnCamera.bottom + 10 + btnMusicSize / 2);
    [_btnBeauty setImage:[UIImage imageNamed:@"beauty_record"] forState:UIControlStateNormal];
    [_btnBeauty setImage:[UIImage imageNamed:@"beauty_record"] forState:UIControlStateHighlighted];
    [_btnBeauty addTarget:self action:@selector(onBtnBeautyClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [_btnBeauty layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop
                                imageTitleSpace:5];
    [self.view addSubview:_btnBeauty];
    _btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnDelete.bounds = CGRectMake(0, 0, BUTTON_CONTROL_SIZE, BUTTON_CONTROL_SIZE);
    _btnDelete.center = CGPointMake(self.view.centerX * 1.5, _btnStartRecord.center.y);
    [_btnDelete setImage:[UIImage imageNamed:@"backDelete"] forState:UIControlStateNormal];
    [_btnDelete setImage:[UIImage imageNamed:@"backDelete"] forState:UIControlStateHighlighted];
    [_btnDelete addTarget:self action:@selector(onBtnDeleteClicked) forControlEvents:UIControlEventTouchUpInside];
    [_btnDelete setTitle:@"删除" forState:0];
    _btnDelete.titleLabel.font = MHRegularFont_12;
    [_btnDelete layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop
                                imageTitleSpace:5];
    [self.view addSubview:_btnDelete];
    
    CGFloat btnNextWidth = 48;
    CGFloat btnNextHeight = 38;
    _btnNext = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnNext.frame = CGRectMake(self.view.right - 15 - btnNextWidth, _btnDelete.y - 5, btnNextWidth, btnNextHeight);
    _btnNext.hidden = YES;
    _btnNext.titleLabel.font = [UIFont systemFontOfSize:14];
    [_btnNext setBackgroundImage:[UIImage imageNamed:@"btn_video_complete"] forState:UIControlStateNormal];
    [_btnNext setBackgroundImage:[UIImage imageNamed:@"btn_video_complete"] forState:UIControlStateHighlighted];
    [_btnNext addTarget:self action:@selector(onBtnDoneClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnNext];
    
    _btnUploadLocal = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnUploadLocal.bounds = CGRectMake(0, 0, 60, 60);
    _btnUploadLocal.center = CGPointMake(self.view.centerX / 2, _btnStartRecord.center.y);
    [_btnUploadLocal setImage:[UIImage imageNamed:@"circle_uploadlocalvideo"] forState:UIControlStateNormal];
    [_btnUploadLocal setImage:[UIImage imageNamed:@"circle_uploadlocalvideo"] forState:UIControlStateHighlighted];
    [_btnUploadLocal addTarget:self action:@selector(onVideoSelectClicked) forControlEvents:UIControlEventTouchUpInside];
    [_btnUploadLocal setTitle:@"上传" forState:0];
    _btnUploadLocal.titleLabel.font = MHRegularFont_12;
    [_btnUploadLocal layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop
                                     imageTitleSpace:5];
    [self.view addSubview:_btnUploadLocal];
    
    _progressView = [[TCVideoRecordProcessView alloc] initWithFrame:CGRectMake(0,_mask_buttom.y - BUTTON_PROGRESS_HEIGHT + 0.5, self.view.frame.size.width, BUTTON_PROGRESS_HEIGHT)];
    _progressView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.2];
    [self.view addSubview:_progressView];
    
    _recordTimeLabel = [[UILabel alloc]init];
    _recordTimeLabel.frame = CGRectMake(0, 0, 100, 100);
    [_recordTimeLabel setText:@"00:00"];
    _recordTimeLabel.font = [UIFont systemFontOfSize:10];
    _recordTimeLabel.textColor = [UIColor whiteColor];
    _recordTimeLabel.textAlignment = NSTextAlignmentLeft;
    [_recordTimeLabel sizeToFit];
    _recordTimeLabel.center = CGPointMake(30, _progressView.frame.origin.y + _recordTimeLabel.frame.size.height + 10);
    [self.view addSubview:_recordTimeLabel];
    [self createSpeedView];
    [self setAspectRatio:VIDEO_ASPECT_RATIO_9_16];
}



-(void)onVideoSelectClicked
{
    QBImagePickerController *imagePickerController = [QBImagePickerController new];
    imagePickerController.delegate = self;
    imagePickerController.mediaType = QBImagePickerMediaTypeVideo;
    imagePickerController.allowsMultipleSelection = NO;
    imagePickerController.maximumNumberOfSelection = 1;
    [self presentViewController:imagePickerController animated:YES completion:NULL];
}

#pragma mark - QBImagePickerControllerDelegate

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets
{
    __block BOOL isPhotoInICloud = NO;
    PHVideoRequestOptions *options = [PHVideoRequestOptions new];
    options.networkAccessAllowed = YES;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    options.progressHandler = ^(double progress, NSError * _Nullable error, BOOL * _Nonnull stop, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            if (!isPhotoInICloud) {
                [MBProgressHUD mh_showTips:@"部分视频正在从iCloud同步，请稍后再试"];
            }else
            {
                
            }
            isPhotoInICloud = YES;
        });
        
        
    };
    
    __weak __typeof(self)weakSelf = self;
    [[PHImageManager defaultManager] requestAVAssetForVideo:assets.firstObject options:options resultHandler:^(AVAsset * _Nullable avAsset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            if (!isPhotoInICloud) {
                [weakSelf dismissViewControllerAnimated:YES completion:^ {
                    [MBProgressHUD mh_hideHUD];
                    if (avAsset) {
                        MHVideoEditViewModel *viewModel = [[MHVideoEditViewModel alloc] initWithServices:weakSelf.viewModel.services params:@{@"videoAsset":[avAsset copy]}];
                        [weakSelf.viewModel.services presentViewModel:viewModel animated:YES completion:nil];
                    }
                }];
            }
        });
    }];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark ---- Video Beauty UI ----
-(void)initBeautyUI
{
    NSUInteger controlHeight = [BeautySettingPanel getHeight];
    CGFloat offset = 0;
    if (@available(iOS 11, *)) {
        offset = [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom;
    }
    _vBeauty = [[BeautySettingPanel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - controlHeight - offset, self.view.frame.size.width, controlHeight)];
    _vBeauty.hidden = YES;
    _vBeauty.delegate = self;
    _vBeauty.pituDelegate = self;
    [_vBeauty resetValues];
    [self.view addSubview:_vBeauty];
}

//加速录制
-(void)createSpeedView
{
    _speedBtnSelectTag = 2;
}

-(void)setSpeedBtnHidden:(BOOL)hidden{
    _speedView.hidden = hidden;
    _speedChangeBtn.hidden = hidden;
}

-(NSString *)getSpeedText:(SpeedMode)speedMode
{
    NSString *text = nil;
    switch (speedMode) {
        case SpeedMode_VerySlow:
            text = @"极慢";
            break;
        case SpeedMode_Slow:
            text = @"慢";
            break;
        case SpeedMode_Standard:
            text = @"标准";
            break;
        case SpeedMode_Quick:
            text = @"快";
            break;
        case SpeedMode_VeryQuick:
            text = @"极快";
            break;
        default:
            break;
    }
    return text;
}

-(void)onBtnRatioClicked:(UIButton *)btn
{
    switch (btn.tag) {
        case VIDEO_ASPECT_RATIO_9_16:
        {
            if (btn.right + 9 == self.view.frame.size.width && [self ratioIsClosure]) {
                _btnRatio11.frame = CGRectOffset(btn.frame, -(30 + BUTTON_CONTROL_SIZE), 0);
                _btnRatio43.frame = CGRectOffset(_btnRatio11.frame, -(30 + BUTTON_CONTROL_SIZE), 0);
                _btnRatio11.hidden = NO;
                _btnRatio43.hidden = NO;
                _labelRatio11.hidden = NO;
                _labelRatio43.hidden = NO;
            }else{
                btn.frame = _btnRatioFrame;
                _btnRatio11.frame = _btnRatioFrame;
                _btnRatio43.frame = _btnRatioFrame;
                _btnRatio11.hidden = YES;
                _btnRatio43.hidden = YES;
                _labelRatio11.hidden = YES;
                _labelRatio43.hidden = YES;
            }
            [self setAspectRatio:VIDEO_ASPECT_RATIO_9_16];
        }
            break;
        case VIDEO_ASPECT_RATIO_1_1:
        {
            if (btn.right + 9 == self.view.frame.size.width && [self ratioIsClosure]) {
                _btnRatio43.frame = CGRectOffset(btn.frame, -(30 + BUTTON_CONTROL_SIZE), 0);
                _btnRatio169.frame = CGRectOffset(_btnRatio43.frame, -(30 + BUTTON_CONTROL_SIZE), 0);
                _btnRatio43.hidden = NO;
                _btnRatio169.hidden = NO;
                _labelRatio43.hidden = NO;
                _labelRatio169.hidden = NO;
            }else{
                btn.frame = _btnRatioFrame;
                _btnRatio43.frame = _btnRatioFrame;
                _btnRatio169.frame = _btnRatioFrame;
                _btnRatio43.hidden = YES;
                _btnRatio169.hidden = YES;
                _labelRatio43.hidden = YES;
                _labelRatio169.hidden = YES;
            }
            [self setAspectRatio:VIDEO_ASPECT_RATIO_1_1];
        }
            
            break;
        case VIDEO_ASPECT_RATIO_3_4:
        {
            if (btn.right + 9 == self.view.frame.size.width && [self ratioIsClosure]) {
                _btnRatio169.frame = CGRectOffset(btn.frame, -(30 + BUTTON_CONTROL_SIZE), 0);
                _btnRatio11.frame = CGRectOffset(_btnRatio169.frame, -(30 + BUTTON_CONTROL_SIZE), 0);
                _btnRatio169.hidden = NO;
                _btnRatio11.hidden = NO;
                _labelRatio169.hidden = NO;
                _labelRatio11.hidden = NO;
            }else{
                btn.frame = _btnRatioFrame;
                _btnRatio169.frame = _btnRatioFrame;
                _btnRatio11.frame = _btnRatioFrame;
                _btnRatio169.hidden = YES;
                _btnRatio11.hidden = YES;
                _labelRatio169.hidden = YES;
                _labelRatio11.hidden = YES;
            }
            [self setAspectRatio:VIDEO_ASPECT_RATIO_3_4];
        }
            
            break;
        default:
            break;
    }
    btn.hidden = NO;
}

- (void)setAspectRatio:(NSInteger)aspectRatio
{
    _aspectRatio = aspectRatio;
    [[TXUGCRecord shareInstance] setAspectRatio:_aspectRatio];
    CGFloat height = 0;
    switch (_aspectRatio) {
        case VIDEO_ASPECT_RATIO_9_16:
            height = _videoRecordView.frame.size.width * 16 / 9;
            break;
        case VIDEO_ASPECT_RATIO_3_4:
            height = _videoRecordView.frame.size.width * 4 / 3;
            break;
        case VIDEO_ASPECT_RATIO_1_1:
            height = _videoRecordView.frame.size.width * 1 / 1;
            break;
        default:
            break;
    }
    [UIView animateWithDuration:0.2 animations:^{
        _videoRecordView.frame = CGRectMake(0, (self.view.height - height) / 2.0, _videoRecordView.frame.size.width, height);;
    }];
    _labelRatio11.frame = CGRectMake(_btnRatio11.x, _btnRatio11.bottom + 4, 44, 14);
    _labelRatio43.frame = CGRectMake(_btnRatio43.x, _btnRatio43.bottom + 4, 44, 14);
    _labelRatio169.frame = CGRectMake(_btnRatio169.x, _btnRatio169.bottom + 4, 44, 14);
}

-(BOOL)ratioIsClosure
{
    if (CGRectEqualToRect(_btnRatio43.frame, _btnRatio11.frame)) {
        return YES;
    }
    return NO;
}

- (void)onBtnMusicClicked
{
    _vBeauty.hidden = YES;
    
    MHBGMListViewModel *listModel = [[MHBGMListViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelUtilKey:self}];
    if (!_bgmListVC) {
        _bgmListVC = [[TCBGMListViewController alloc] initWithViewModel:listModel];
        [_bgmListVC setBGMControllerListener:self];
    }
    [self.viewModel.services presentViewModel:listModel animated:YES completion:^{
        
    }];
}

-(void)onBtnSpeedClicked:(UIButton *)btn
{
    [UIView animateWithDuration:0.5 animations:^{
        _speedBtnSelectTag = btn.tag;
        if (_speedBtnSelectTag == 0) {
            [_speedChangeBtn setBackgroundImage:[UIImage imageNamed:@"speedChange_left"] forState:UIControlStateNormal];
        }else if (_speedBtnSelectTag == 4){
            [_speedChangeBtn setBackgroundImage:[UIImage imageNamed:@"speedChange_right"] forState:UIControlStateNormal];
        }else{
            [_speedChangeBtn setBackgroundImage:[UIImage imageNamed:@"speedChange_center"] forState:UIControlStateNormal];
        }
        CGRect rect = [_speedView convertRect:btn.frame toView:self.view];
        _speedChangeBtn.frame = CGRectMake(rect.origin.x - (BUTTON_SPEED_CHANGE_WIDTH - rect.size.width) / 2, rect.origin.y - (BUTTON_SPEED_CHANGE_HEIGHT - rect.size.height) / 2, BUTTON_SPEED_CHANGE_WIDTH, BUTTON_SPEED_CHANGE_HEIGHT);
        [_speedChangeBtn setTitle:[self getSpeedText:(SpeedMode)_speedBtnSelectTag] forState:UIControlStateNormal];
        [_speedChangeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }];
}

-(void)setSpeedRate{
    switch ((SpeedMode)_speedBtnSelectTag) {
        case SpeedMode_VerySlow:
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_SLOWEST];
            break;
        case SpeedMode_Slow:
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_SLOW];
            break;
        case SpeedMode_Standard:
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_NOMAL];
            break;
        case SpeedMode_Quick:
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_FAST];
            break;
        case SpeedMode_VeryQuick:
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_FASTEST];
            break;
        default:
            break;
    }
}

-(void)onBtnFlashClicked
{
    if (_isFlash) {
        [_btnFlash setImage:[UIImage imageNamed:@"closeFlash"] forState:UIControlStateNormal];
        [_btnFlash setImage:[UIImage imageNamed:@"closeFlash_hover"] forState:UIControlStateHighlighted];
    }else{
        [_btnFlash setImage:[UIImage imageNamed:@"openFlash"] forState:UIControlStateNormal];
        [_btnFlash setImage:[UIImage imageNamed:@"openFlash_hover"] forState:UIControlStateHighlighted];
    }
    _isFlash = !_isFlash;
    [[TXUGCRecord shareInstance] toggleTorch:_isFlash];
}

-(void)onBtnDeleteClicked
{
    if (_videoRecording && !_isPaused) {
        [self onBtnRecordStartClicked];
    }
    if (0 == _deleteCount) {
        [_progressView prepareDeletePart];
    }else{
        [_progressView comfirmDeletePart];
        [[TXUGCRecord shareInstance].partsManager deleteLastPart];
        _isBackDelete = YES;
    }
    if (2 == ++ _deleteCount) {
        _deleteCount = 0;
    }
}

-(void)onBtnRecordStartClicked
{
    
    if (self.BGMPath.length <= 0) {
        [self onVoiceValueChange:1];
        [self onBGMValueChange:0];
    }else
    {
        [self onBGMValueChange:1];
        [self onVoiceValueChange:0];
        
    }
    if (!_videoRecording)
    {
        
        
        [self startVideoRecord];
    }
    else
    {        
        if (_isPaused) {
            [self setSpeedRate];
            
            if (_bgmRecording) {
                [self resumeBGM];
            }else{
                [self playBGM:_bgmBeginTime];
                _bgmRecording = YES;
            }
            [[TXUGCRecord shareInstance] resumeRecord];
            
            [_btnStartRecord setImage:[UIImage imageNamed:@"pause_record"] forState:UIControlStateNormal];
            [_btnStartRecord setBackgroundImage:[UIImage imageNamed:@"pause_ring"] forState:UIControlStateNormal];
            _btnStartRecord.bounds = CGRectMake(0, 0, BUTTON_RECORD_SIZE * 0.85, BUTTON_RECORD_SIZE * 0.85);
            
            if (_deleteCount == 1) {
                [_progressView cancelDelete];
                _deleteCount = 0;
            }
            [self setSpeedBtnHidden:YES];
            
            _isPaused = NO;
        }
        else {
            [[TXUGCRecord shareInstance] pauseRecord];
            [self pauseBGM];
            
            [_btnStartRecord setImage:[UIImage imageNamed:@"start_record"] forState:UIControlStateNormal];
            [_btnStartRecord setBackgroundImage:[UIImage imageNamed:@"start_ring"] forState:UIControlStateNormal];
            _btnStartRecord.bounds = CGRectMake(0, 0, BUTTON_RECORD_SIZE, BUTTON_RECORD_SIZE);
            
            [_progressView pause];
            [self setSpeedBtnHidden:NO];
            
            _isPaused = YES;
        }
    }
}

- (void)onBtnDoneClicked
{
    if (!_videoRecording)
        return;
    
    [self stopVideoRecord];
}



-(void)startCameraPreview
{
    if (_cameraPreviewing == NO)
    {
        //简单设置
        //                TXUGCSimpleConfig * param = [[TXUGCSimpleConfig alloc] init];
        //                param.videoQuality = VIDEO_QUALITY_HIGH;
        //                param.minDuration = MIN_RECORD_TIME;
        //                param.maxDuration = MAX_RECORD_TIME;
        //                [[TXUGCRecord shareInstance] startCameraSimple:param preview:_videoRecordView];
        //自定义设置
        
        TXUGCCustomConfig * param = [[TXUGCCustomConfig alloc] init];
        param.videoResolution =  VIDEO_RESOLUTION_720_1280;
        param.videoFPS = 20;  //每秒显示多少帧
        param.videoBitratePIN = MHVideoBitratePIN; //码率
        param.GOP = 3;
        
        param.enableAEC = YES;
        param.minDuration = MIN_RECORD_TIME;
        param.maxDuration = MAX_RECORD_TIME;
       [[TXUGCRecord shareInstance] startCameraCustom:param preview:_videoRecordView];
        [[TXUGCRecord shareInstance] setBeautyStyle:0 beautyLevel:_beautyDepth whitenessLevel:_whitenDepth ruddinessLevel:_redDepth];
#if POD_PITU
        [self motionTmplSelected:_materialID];
#endif
        _cameraPreviewing = YES;
    }
}

-(void)stopCameraPreview
{
    if (_cameraPreviewing == YES)
    {
        [[TXUGCRecord shareInstance] stopCameraPreview];
        _cameraPreviewing = NO;
    }
}

-(void)startVideoRecord
{
    [self refreshRecordTime:0];
    [self startCameraPreview];
    [self setSpeedRate];
    int result = [[TXUGCRecord shareInstance] startRecord];
    if(0 != result)
    {
        if(-1 == result) [self alert:@"启动录制失败" msg:@"正在录制短视频"];
        if(-3 == result) [self alert:@"启动录制失败" msg:@"请检查摄像头权限是否打开"];
        if(-4 == result) [self alert:@"启动录制失败" msg:@"请检查麦克风权限是否打开"];
        if(-5 == result) [self alert:@"启动录制失败" msg:@"licence 验证失败"];
    }else{
        
        [self playBGM:_bgmBeginTime];
        _bgmRecording = YES;
        _videoRecording = YES;
        _isPaused = NO;
        [self setSpeedBtnHidden:YES];
        [_btnStartRecord setImage:[UIImage imageNamed:@"pause_record"] forState:UIControlStateNormal];
        [_btnStartRecord setBackgroundImage:[UIImage imageNamed:@"pause_record"] forState:UIControlStateNormal];
        _btnStartRecord.bounds = CGRectMake(0, 0, BUTTON_RECORD_SIZE * 0.85, BUTTON_RECORD_SIZE * 0.85);
    }
}

- (void)resetBGM {
    self.BGMPath = nil;
    _bgmRecording = NO;
    [[TXUGCRecord shareInstance] stopBGM];
    [[TXUGCRecord shareInstance] setBGM:nil];

}

-(void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)stopVideoRecord
{
    //调用partsManager快速合成视频，不破坏录制状态，下次返回后可以接着录制（注意需要先暂停视频录制）
//    @autoreleasepool {
        if ([TXUGCRecord shareInstance].partsManager.getVideoPathList.count > 0) {
            
//            if(0 == [[TXUGCRecord shareInstance].partsManager joinAllParts:_videoOutputPath]){
//                self.viewModel.musicPath = self.BGMPath;
//                [self.viewModel.pushToEditCommand execute:_videoOutputPath];
//                [[TXUGCRecord shareInstance] pauseAudioSession];
//            }
            
            __weak __typeof(self)weakSelf = self;
            [[TXUGCRecord shareInstance].partsManager joinAllParts:_videoOutputPath complete:^(int result) {
                if (result == 0) {
                    weakSelf.viewModel.musicPath = weakSelf.BGMPath;
                    [weakSelf.viewModel.pushToEditCommand execute: self->_videoOutputPath];
                    [[TXUGCRecord shareInstance] pauseAudioSession];
                }
            }];
//    }
    
//                __weak __typeof(self)weakSelf = self;
//                [[TXUGCRecord shareInstance].partsManager joinAllParts:_videoOutputPath complete:^(int result) {
//                    if (result == 0) {
//                        weakSelf.viewModel.musicPath = weakSelf.BGMPath;
//                        [weakSelf.viewModel.pushToEditCommand execute: self->_videoOutputPath];
//                        [[TXUGCRecord shareInstance] pauseAudioSession];
//                    }
//                }];
        
//                if(0 == [[TXUGCRecord shareInstance].partsManager joinAllParts:_videoOutputPath]){
//
//                }
    }
}

-(void)resetVideoUI
{
    [_progressView deleteAllPart];
    [_btnStartRecord setImage:[UIImage imageNamed:@"start_record"] forState:UIControlStateNormal];
    [_btnStartRecord setBackgroundImage:[UIImage imageNamed:@"start_ring"] forState:UIControlStateNormal];
    _btnStartRecord.bounds = CGRectMake(0, 0, BUTTON_RECORD_SIZE, BUTTON_RECORD_SIZE);
    
    [self resetSpeedBtn];
    [_musicView resetVolume];
    
    _btnRatio169.enabled = YES;
    _btnRatio43.enabled = YES;
    _btnRatio11.enabled = YES;
    _btnMusic.enabled = YES;
    _btnNext.enabled = YES;
    _isPaused = NO;
    _videoRecording = NO;
}

-(void)resetSpeedBtn{
    [self setSpeedBtnHidden:NO];
    for(UIButton *btn in _speedBtnList){
        if (btn.tag == 2) {
            [self onBtnSpeedClicked:btn];
        }
    }
}



-(void)onBtnCameraClicked
{
    _cameraFront = !_cameraFront;
    [[TXUGCRecord shareInstance] switchCamera:_cameraFront];
    if (_cameraFront) {
        [_btnFlash setImage:[UIImage imageNamed:@"openFlash_disable"] forState:UIControlStateNormal];
        _btnFlash.enabled = NO;
    }else{
        if (_isFlash) {
            [_btnFlash setImage:[UIImage imageNamed:@"openFlash"] forState:UIControlStateNormal];
            [_btnFlash setImage:[UIImage imageNamed:@"openFlash_hover"] forState:UIControlStateHighlighted];
        }else{
            [_btnFlash setImage:[UIImage imageNamed:@"closeFlash"] forState:UIControlStateNormal];
            [_btnFlash setImage:[UIImage imageNamed:@"closeFlash_hover"] forState:UIControlStateHighlighted];
        }
        _btnFlash.enabled = YES;
    }
    [[TXUGCRecord shareInstance] toggleTorch:_isFlash];
}

-(void)onBtnLampClicked
{
    _lampOpened = !_lampOpened;
    
    BOOL result = [[TXUGCRecord shareInstance] toggleTorch:_lampOpened];
    if (result == NO)
    {
        _lampOpened = !_lampOpened;
        [self toastTip:@"闪光灯启动失败"];
    }
    
    if (_lampOpened)
    {
        [_btnLamp setImage:[UIImage imageNamed:@"lamp_press"] forState:UIControlStateNormal];
    }else
    {
        [_btnLamp setImage:[UIImage imageNamed:@"lamp"] forState:UIControlStateNormal];
    }
}

-(void)onBtnBeautyClicked
{
    _vBeautyShow = !_vBeautyShow;
    _musicView.hidden = YES;
    _vBeauty.hidden = !_vBeautyShow;
    [self hideBottomView:_vBeautyShow];
}

- (void) touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (_vBeautyShow)
    {
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint _touchPoint = [touch locationInView:self.view];
        if (NO == CGRectContainsPoint(_vBeauty.frame, _touchPoint))
        {
            [self onBtnBeautyClicked];
        }
    }
    //    if (!_musicView.hidden) {
    //        CGPoint _touchPoint = [[[event allTouches] anyObject] locationInView:self.view];
    //        if (NO == CGRectContainsPoint(_musicView.frame, _touchPoint)){
    //            _musicView.hidden = !_musicView.hidden;
    //            [self hideBottomView:!_musicView.hidden];
    //        }
    //    }
}

- (void)hideBottomView:(BOOL)bHide
{
    _speedView.hidden = bHide;
    _speedChangeBtn.hidden = bHide;
    _btnFlash.hidden = bHide;
    //    _btnCamera.hidden = bHide;
    _btnStartRecord.hidden = bHide;
    
    if (bHide) {
        
        
        
    }
    //    if (_currentRecordTime <= 0) {
    //        _btnDelete.hidden = YES;
    //        _btnUploadLocal.hidden = false;
    //    }else
    //    {
    //        _btnDelete.hidden = bHide;
    //        _btnUploadLocal.hidden = YES;
    //    }
    //    if (bHide) {
    //        _btnDelete.hidden = YES;
    //        _btnUploadLocal.hidden = YES;
    //    }
    _btnDelete.hidden = bHide;
    _btnUploadLocal.hidden = bHide;
    _progressView.hidden = bHide;
    _recordTimeLabel.hidden = bHide;
    _mask_buttom.hidden = bHide;
}

-(void)selectBeautyPage:(UIButton *)button
{
    switch (button.tag)
    {
        case 0:
            _beautyPage.hidden = NO;
            _beautyBtn.selected = YES;
            
            _filterPage.hidden = YES;
            _filterBtn.selected = NO;
            
            _motionBtn.selected = NO;
            _greenBtn.selected  = NO;
            _tmplBar.hidden = YES;
            _greenPickerView.hidden = YES;
            
            break;
            
        case 1:
            _beautyPage.hidden = YES;
            _beautyBtn.selected = NO;
            
            _filterPage.hidden = NO;
            _filterBtn.selected = YES;
            
            [_filterPickerView scrollToElement:_filterIndex animated:NO];
            
            _motionBtn.selected = NO;
            _greenBtn.selected  = NO;
            _tmplBar.hidden = YES;
            _greenPickerView.hidden = YES;
            break;
            
        case 2: {
            _beautyPage.hidden = YES;
            _beautyBtn.selected = NO;
            
            _filterPage.hidden = YES;
            _filterBtn.selected = NO;
            
            _motionBtn.selected = YES;
            _greenBtn.selected  = NO;
            _tmplBar.hidden = NO;
            _greenPickerView.hidden = YES;
        }
            break;
        case 3: {
            _beautyPage.hidden = YES;
            _beautyBtn.selected = NO;
            
            _filterPage.hidden = YES;
            _filterBtn.selected = NO;
            
            _motionBtn.selected = NO;
            _greenBtn.selected  = YES;
            _tmplBar.hidden = YES;
            _greenPickerView.hidden = NO;
            [_greenPickerView scrollToElement:_greenIndex animated:NO];
        }
    }
}

-(void)sliderValueChange:(UISlider*)obj
{
    int tag = (int)obj.tag;
    float value = obj.value;
    
    switch (tag) {
        case 0:
            _beautyDepth = value;
            [[TXUGCRecord shareInstance] setBeautyStyle:0 beautyLevel:_beautyDepth whitenessLevel:_whitenDepth ruddinessLevel:_redDepth];
            break;
            
        case 1:
            _whitenDepth = value;
            [[TXUGCRecord shareInstance] setBeautyStyle:0 beautyLevel:_beautyDepth whitenessLevel:_whitenDepth ruddinessLevel:_redDepth];
            break;
        case 2: //大眼
            _eye_level = value;
            [[TXUGCRecord shareInstance] setEyeScaleLevel:_eye_level];
            break;
        case 3:  //瘦脸
            _face_level = value;
            [[TXUGCRecord shareInstance] setFaceScaleLevel:_face_level];
            break;
        default:
            break;
    }
}

-(void)refreshRecordTime:(CGFloat)second
{
    self.currentRecordTime = second;
    [_progressView update:_currentRecordTime / MAX_RECORD_TIME];
    NSInteger min = (int)_currentRecordTime / 60;
    NSInteger sec = (int)_currentRecordTime % 60;
    
    [_recordTimeLabel setText:[NSString stringWithFormat:@"%02ld:%02ld", min, sec]];
    [_recordTimeLabel sizeToFit];
}

#pragma mark TXVideoJoinerListener
-(void) onJoinComplete:(TXJoinerResult *)result
{
    if (_appForeground && result.retCode == RECORD_RESULT_OK) {
//        [_hub hide:YES];
        self.viewModel.musicPath = self.BGMPath;
        [self.viewModel.pushToEditCommand execute: _videoOutputPath];
        [[TXUGCRecord shareInstance] pauseAudioSession];
    }
}

#pragma mark TXUGCRecordListener
-(void) onRecordProgress:(NSInteger)milliSecond;
{
    [self refreshRecordTime: milliSecond / 1000.0];
    if(0 == milliSecond / 1000.0){
        _btnRatio169.enabled = YES;
        _btnRatio43.enabled = YES;
        _btnRatio11.enabled = YES;
        _btnMusic.enabled = YES;
        _btnNext.hidden = YES;
    }else{
        _btnRatio169.enabled = NO;
        _btnRatio43.enabled = NO;
        _btnRatio11.enabled = NO;
        _btnMusic.enabled = NO;
    }
    if (milliSecond / 1000.0 >= MIN_RECORD_TIME) {
        _btnNext.hidden = NO;
    }
}

-(void) onRecordComplete:(TXUGCRecordResult*)result;
{
    if (_appForeground)
    {
        if (_currentRecordTime >= MIN_RECORD_TIME)
        {
            if (result.retCode != UGC_RECORD_RESULT_FAILED) {
                self.viewModel.musicPath = self.BGMPath;
                [self.viewModel.pushToEditCommand execute: result.videoPath];
                 [[TXUGCRecord shareInstance].partsManager deleteAllParts];
//                [self resetBGM];
            }else{
                [self toastTip:@"录制失败"];
            }
        } else {
            //            [self toastTip:@"至少要录够5秒"];
        }
    }
}

#if POD_PITU
- (void)motionTmplSelected:(NSString *)materialID {
    if (materialID == nil) {
        [MCTip hideText];
    }
    _materialID = materialID;
    if ([MaterialManager isOnlinePackage:materialID]) {
        [[TXUGCRecord shareInstance] selectMotionTmpl:materialID inDir:[MaterialManager packageDownloadDir]];
    } else {
        NSString *localPackageDir = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Resource"];
        [[TXUGCRecord shareInstance] selectMotionTmpl:materialID inDir:localPackageDir];
    }
}
#endif
#pragma mark - HorizontalPickerView DataSource
- (NSInteger)numberOfElementsInHorizontalPickerView:(V8HorizontalPickerView *)picker {
    if (picker == _greenPickerView) {
        return [_greenArray count];
    } else if(picker == _filterPickerView) {
        return [_filterArray count];
    }
    return 0;
}

#pragma mark - BeautyLoadPituDelegate
- (void)onLoadPituStart
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        _hub.mode = MBProgressHUDModeText;
        _hub.labelText = @"开始加载资源";
    });
}
- (void)onLoadPituProgress:(CGFloat)progress
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _hub.labelText = [NSString stringWithFormat:@"正在加载资源%d %%",(int)(progress * 100)];
    });
}
- (void)onLoadPituFinished
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _hub.labelText = @"资源加载成功";
        [_hub hide:YES afterDelay:1];
    });
}
- (void)onLoadPituFailed
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _hub.labelText = @"资源加载失败";
        [_hub hide:YES afterDelay:1];
    });
}

#pragma mark - BeautySettingPanelDelegate
- (void)onSetBeautyStyle:(int)beautyStyle beautyLevel:(float)beautyLevel whitenessLevel:(float)whitenessLevel ruddinessLevel:(float)ruddinessLevel{
    [[TXUGCRecord shareInstance] setBeautyStyle:beautyStyle beautyLevel:beautyLevel whitenessLevel:whitenessLevel ruddinessLevel:ruddinessLevel];
}

- (void)onSetEyeScaleLevel:(float)eyeScaleLevel
{
    [[TXUGCRecord shareInstance] setEyeScaleLevel:eyeScaleLevel];
}

- (void)onSetFaceScaleLevel:(float)faceScaleLevel
{
    [[TXUGCRecord shareInstance] setFaceScaleLevel:faceScaleLevel];
}

- (void)onSetFilter:(UIImage*)filterImage
{
    [[TXUGCRecord shareInstance] setFilter:filterImage];
}

- (void)onSetGreenScreenFile:(NSURL *)file
{
    [[TXUGCRecord shareInstance] setGreenScreenFile:file];
}

- (void)onSelectMotionTmpl:(NSString *)tmplName inDir:(NSString *)tmplDir
{
    [[TXUGCRecord shareInstance] selectMotionTmpl:tmplName inDir:tmplDir];
}

- (void)onSetFaceVLevel:(float)faceVLevel{
    [[TXUGCRecord shareInstance] setFaceVLevel:faceVLevel];
}

- (void)onSetChinLevel:(float)chinLevel{
    [[TXUGCRecord shareInstance] setChinLevel:chinLevel];
}

- (void)onSetNoseSlimLevel:(float)slimLevel{
    [[TXUGCRecord shareInstance] setNoseSlimLevel:slimLevel];
}

- (void)onSetFaceShortLevel:(float)faceShortlevel{
    [[TXUGCRecord shareInstance] setFaceShortLevel:faceShortlevel];
}

- (void)onSetMixLevel:(float)mixLevel{
    [[TXUGCRecord shareInstance] setSpecialRatio:mixLevel / 10.0];
}

- (void)onSetFaceBeautyLevel:(float)beautyLevel {
    // None
}


#pragma mark TCBGMControllerListener
-(void) onBGMControllerPlay:(NSString*) path{
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [self onSetBGM:path];
        [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_NOMAL];
//        [self playBGM:0];
    }
}

#pragma mark - VideoRecordMusicViewDelegate
-(void)selectAudioEffect:(NSInteger)index
{
    [[TXUGCRecord shareInstance] setReverbType:index];
}

-(void)selectAudioEffect2:(NSInteger)index
{
    [[TXUGCRecord shareInstance] setVoiceChangerType:index];
}

-(void)onBtnMusicSelected
{
    MHBGMListViewModel *listModel = [[MHBGMListViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelUtilKey:self}];
    if (!_bgmListVC) {
        _bgmListVC = [[TCBGMListViewController alloc] initWithViewModel:listModel];
        [_bgmListVC setBGMControllerListener:self];
    }
    [self.viewModel.services presentViewModel:listModel animated:YES completion:^{
        
    }];
    
}

-(void)onBtnMusicStoped
{
    self.BGMPath = nil;
    _bgmRecording = NO;
    [[TXUGCRecord shareInstance] stopBGM];
    if (!_musicView.hidden) {
        _musicView.hidden = !_musicView.hidden;
        [self hideBottomView:!_musicView.hidden];
    }
}

-(void)onBGMValueChange:(CGFloat)value
{
    [[TXUGCRecord shareInstance] setBGMVolume:value];
}

-(void)onVoiceValueChange:(CGFloat)value
{
    [[TXUGCRecord shareInstance] setMicVolume:value];
    
}

-(void)onBGMRangeChange:(CGFloat)startPercent endPercent:(CGFloat)endPercent
{
    _bgmRecording = NO;
    [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_NOMAL];
    [self playBGM:_BGMDuration * startPercent toTime:_BGMDuration * endPercent];
}

-(void)onSetBGM:(NSString *)path
{
    self.BGMPath = path;
    _BGMDuration =  [[TXUGCRecord shareInstance] setBGM:self.BGMPath];
    NSString *musicName = [[[path componentsSeparatedByString:@"/"] lastObject] stringByDeletingPathExtension];
    _bgmRecording = NO;
    [_btnMusic setTitle:musicName forState:0];
    [_btnMusic sizeToFit];
    _btnMusic.center = CGPointMake(self.view.centerX,  20 + BUTTON_CONTROL_SIZE / 2 + zh_topSafeAreaHeight());
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}


-(void)playBGM:(CGFloat)beginTime{
    if (self.BGMPath != nil) {
        BOOL isSuccess =  [[TXUGCRecord shareInstance] playBGMFromTime:beginTime toTime:_BGMDuration withBeginNotify:^(NSInteger errCode) {
            
        } withProgressNotify:^(NSInteger progressMS, NSInteger durationMS) {
            
        } andCompleteNotify:^(NSInteger errCode) {
            
        }];
        _bgmBeginTime = beginTime;
    }
}

-(void)playBGM:(CGFloat)beginTime toTime:(CGFloat)endTime
{
    if (self.BGMPath != nil) {
       BOOL isSuccess = [[TXUGCRecord shareInstance] playBGMFromTime:beginTime toTime:endTime withBeginNotify:^(NSInteger errCode) {
            
        } withProgressNotify:^(NSInteger progressMS, NSInteger durationMS) {
            
        } andCompleteNotify:^(NSInteger errCode) {
            
        }];
        _bgmBeginTime = beginTime;
    }
}

-(void)pauseBGM{
    if (self.BGMPath != nil) {
        [[TXUGCRecord shareInstance] pauseBGM];
    }
}

- (void)resumeBGM
{
    if (self.BGMPath != nil) {
        [[TXUGCRecord shareInstance] resumeBGM];
    }
}


#pragma mark - HorizontalPickerView Delegate Methods
- (UIView *)horizontalPickerView:(V8HorizontalPickerView *)picker viewForElementAtIndex:(NSInteger)index {
    if (picker == _greenPickerView) {
        V8LabelNode *v = [_greenArray objectAtIndex:index];
        return [[UIImageView alloc] initWithImage:v.face];
    } else if(picker == _filterPickerView) {
        V8LabelNode *v = [_filterArray objectAtIndex:index];
        return [[UIImageView alloc] initWithImage:v.face];
    }
    return nil;
}

- (NSInteger) horizontalPickerView:(V8HorizontalPickerView *)picker widthForElementAtIndex:(NSInteger)index {
    if (picker == _greenPickerView) {
        return 70;
    }
    return 90;
}

- (void)horizontalPickerView:(V8HorizontalPickerView *)picker didSelectElementAtIndex:(NSInteger)index
{
    if (picker == _greenPickerView) {
        _greenIndex = index;
        V8LabelNode *v = [_greenArray objectAtIndex:index];
        [[TXUGCRecord shareInstance] setGreenScreenFile:v.file];
        return;
    }
    if (picker == _filterPickerView) {
        _filterIndex = index;
        
        [self setFilter:_filterIndex];
    }
}

- (void)setFilter:(int)index
{
    NSString* lookupFileName = @"";
    
    switch (index) {
        case FilterType_None:
            break;
        case FilterType_white:
            lookupFileName = @"filter_white";
            break;
        case FilterType_langman:
            lookupFileName = @"filter_langman";
            break;
        case FilterType_qingxin:
            lookupFileName = @"filter_qingxin";
            break;
        case FilterType_weimei:
            lookupFileName = @"filter_weimei";
            break;
        case FilterType_fennen:
            lookupFileName = @"filter_fennen";
            break;
        case FilterType_huaijiu:
            lookupFileName = @"filter_huaijiu";
            break;
        case FilterType_landiao:
            lookupFileName = @"filter_landiao";
            break;
        case FilterType_qingliang:
            lookupFileName = @"filter_qingliang";
            break;
        case FilterType_rixi:
            lookupFileName = @"filter_rixi";
            break;
        default:
            break;
    }
    
    NSString * path = [[NSBundle mainBundle] pathForResource:lookupFileName ofType:@"png"];
    if (path != nil && index != FilterType_None)
    {
        [[TXUGCRecord shareInstance] setFilter:[UIImage imageWithContentsOfFile:path]];
    }
    else
    {
        [[TXUGCRecord shareInstance] setFilter:nil];
    }
}

#pragma mark - Misc Methods

- (float) heightForString:(UITextView *)textView andWidth:(float)width{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}

- (void) toastTip:(NSString*)toastInfo
{
    CGRect frameRC = [[UIScreen mainScreen] bounds];
    frameRC.origin.y = frameRC.size.height - 100;
    frameRC.size.height -= 100;
    __block UITextView * toastView = [[UITextView alloc] init];
    
    toastView.editable = NO;
    toastView.selectable = NO;
    
    frameRC.size.height = [self heightForString:toastView andWidth:frameRC.size.width];
    
    toastView.frame = frameRC;
    
    toastView.text = toastInfo;
    toastView.backgroundColor = [UIColor whiteColor];
    toastView.alpha = 0.5;
    
    [self.view addSubview:toastView];
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
    
    dispatch_after(popTime, dispatch_get_main_queue(), ^(){
        [toastView removeFromSuperview];
        toastView = nil;
    });
}

@end
